package com.caifu.shiro.realm;


import com.caifu.pojo.SysUser;
import com.caifu.service.LoginService;
import com.caifu.shiro.exception.UserBlockedException;
import com.caifu.shiro.exception.UserNotExistsException;
import com.caifu.shiro.exception.UserPasswordNotMatchException;
import com.caifu.shiro.exception.UserPasswordRetryLimitExceedException;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 自定义realm
 *
 * @author tww
 * ClassName: CustormerRealm.java、
 * createTime: 2021年01月02日 13:09:32
 **/
public class CustormerRealm extends AuthorizingRealm {


    @Autowired
    private LoginService loginService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String userName = token.getPrincipal().toString();
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        String password = "";
        if (upToken.getPassword() != null) {
            password = new String(upToken.getPassword());
        }
        SysUser sysUser = null;
        try {
            //登录
            sysUser = loginService.login(userName, password);
        } catch (UserNotExistsException e) {
            throw new UnknownAccountException(e.getMessage(), e);
        } catch (UserBlockedException e) {
            throw new LockedAccountException(e.getMessage(), e);
        } catch (UserPasswordRetryLimitExceedException e) {
            throw new ExcessiveAttemptsException(e.getMessage(), e);
        } catch (UserPasswordNotMatchException e) {
            throw new IncorrectCredentialsException(e.getMessage(), e);
        }

        return new SimpleAuthenticationInfo(sysUser, sysUser.getPaw(), getName());

    }
}
